package com.example.skillcinema.ui.screens.search

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.example.skillcinema.R
import com.example.skillcinema.adapters.FootLoadStateAdapter
import com.example.skillcinema.adapters.StaffFilmographyPagedAdapter
import com.example.skillcinema.adapters.YearPickerRecyclerViewAdapter
import com.example.skillcinema.databinding.FragmentSearchBinding
import com.example.skillcinema.db.enums.FilmOrderTypes
import com.example.skillcinema.db.responses.FiltersCountriesResponse
import com.example.skillcinema.db.responses.FiltersGenresResponse
import com.example.skillcinema.ui.screens.main.FilmDetailsFragment
import com.example.skillcinema.ui.screens.search.viewModels.SearchViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

class SearchFragment : Fragment() {
    private var _binding: FragmentSearchBinding? = null
    private val binding get() = _binding!!
    private val viewModel: SearchViewModel by activityViewModels()

    private var searchJob: Job? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSearchBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        restoreSearchSettings()

        val adapter = StaffFilmographyPagedAdapter { filmClicked(it) }
        binding.searchResultRecyclerView.adapter =
            adapter.withLoadStateFooter(FootLoadStateAdapter())

        binding.swipeToRefresh.setOnRefreshListener { adapter.refresh() }
        adapter.loadStateFlow.onEach {
            binding.swipeToRefresh.isRefreshing = it.refresh == LoadState.Loading
        }
            .launchIn(viewLifecycleOwner.lifecycleScope)

        binding.searchOptionButton.setOnClickListener { showOptions() }

        binding.searchEditText.addTextChangedListener { text ->
            searchJob?.cancel()
            searchJob = lifecycleScope.launch {
                delay(600)
                viewModel.onSearchQueryChanged(text.toString())
            }
        }

        lifecycleScope.launch {
            viewModel.filmPaged.collectLatest { adapter.submitData(it) }
        }
    }

//    private fun saveSearchSettings() {
//        val prefs = requireContext().getSharedPreferences("search_prefs", Context.MODE_PRIVATE)
//        with(prefs.edit()) {
//            putString("searchKeyWord", binding.searchEditText.text.toString())
//
//            putInt("countryId", viewModel.country?.id ?: -1)
//            putInt("genreId", viewModel.genre?.id ?: -1)
//            putInt("yearStart", viewModel.year?.first ?: -1)
//            putInt("yearEnd", viewModel.year?.second ?: -1)
//            putFloat("rateMin", viewModel.rate?.first ?: -1f)
//            putFloat("rateMax", viewModel.rate?.second ?: -1f)
//            putString("orderType", viewModel.orderType.name)
//            putBoolean("isWatched", viewModel.isWatched)
//
//            apply()
//        }
//    }

//    private fun restoreSearchSettings() {
//        val prefs = requireContext().getSharedPreferences("search_prefs", Context.MODE_PRIVATE)
//
//        binding.searchEditText.setText(prefs.getString("searchKeyWord", ""))
//
//        val countryId = prefs.getInt("countryId", -1)
//        viewModel.country = if (countryId != -1) FiltersCountriesResponse(countryId, "") else null
//
//        val genreId = prefs.getInt("genreId", -1)
//        viewModel.genre = if (genreId != -1) FiltersGenresResponse(genreId, "") else null
//
//        val yearStart = prefs.getInt("yearStart", -1)
//        val yearEnd = prefs.getInt("yearEnd", -1)
//        viewModel.year = if (yearStart != -1 && yearEnd != -1) yearStart to yearEnd else null
//
//        val rateMin = prefs.getFloat("rateMin", -1f)
//        val rateMax = prefs.getFloat("rateMax", -1f)
//        viewModel.rate = if (rateMin != -1f && rateMax != -1f) rateMin to rateMax else null
//
//        viewModel.orderType =
//            FilmOrderTypes.valueOf(prefs.getString("orderType", FilmOrderTypes.YEAR.name)!!)
//        viewModel.isWatched = prefs.getBoolean("isWatched", false)
//    }

    private fun filmClicked(id: Int) {
        val bundle = Bundle().apply { putInt(FilmDetailsFragment.FILM_ID_ARG, id) }
        findNavController().navigate(R.id.action_searchFragment_to_filmDetailsFragment, bundle)
    }

    private fun showOptions() {
        findNavController().navigate(R.id.action_searchFragment_to_searchOptionsFragment)
    }

    override fun onDestroyView() {
        super.onDestroyView()
//        saveSearchSettings()
        _binding = null
    }
}